package cn.bellychang.leetcode.question234;

/**
 * @author ChangLiang
 * @date 2020/10/30
 */

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
public class Solution {

    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        // 快指针 一次 走两步
        // 慢指针 一次 走一步 并且将前面的反序
        // 当快指针走完 慢指针正好走到中点
        // 反向指针向回走 慢指针继续向前走

        ListNode fast = head;
        ListNode slow = head;
        // 这里是关键 空节点 统一逻辑
        ListNode prev = null;
        while (fast != null && fast.next!=null) {

            fast = fast.next.next;
            ListNode next = slow.next;
            slow.next = prev;
            prev = slow;
            slow = next;
        }
        // 兼容 奇数个 和 偶数个 为空说明是偶数个
        if (fast != null) {
            slow = slow.next;
        }
        while (slow != null) {
            if (slow.val != prev.val) {
                return false;
            }
            slow = slow.next;
            prev = prev.next;
        }
        return true;
    }
}
